<template>
  <!-- 首页 -->

  <div class="dashboard">
    <a-skeleton :loading="loading" active>
      <top-bar />
    </a-skeleton>
  <div class="navbar">
      <div
              v-for="(item, index) in items" 
              :key="index" 
              class="navbar-item" 
              :class="{ selected: selectedItem === index }"
              @click.prevent="selectItem(index,item.link)"
          >
              {{ item.name }}
  </div>
  </div>
  <!-- 下面的 -->
  <div class="box">
    <div class="nested-boxes">
      <div class="nested-box">学生名单</div>
      <div class="nested-box">2024级2班</div>
    </div>
    <!-- <p>这是一个宽1820px，高880px的盒子。</p> -->

     <!-- 按钮 -->
      <div class="thedit" v-if="tableData=='' && handadd!==false && havelist==false">
          <div class="eidt1" @click="tapadd">
            <img src="/public/thebtn.png" width="28px" height="28px" class="write1">
                <p class="text1">手动编辑</p>
          </div>
          <div class="eidt2" @click="tapinclude">
            <input  type="file" @change="handle" accept=".xlsx,.xls"  style="display: none" ref="fileInput"/>
           <img src="/public/thebtn.png" width="28px" height="28px" class="write2">
              <p class="text2">外部导入</p>
          </div>
      </div>
      <!-- 为空时 -->
        <div class="empy" v-if="tableData=='' && handadd!==false && havelist==false  ">
          <img src="/public/empy.png" alt="">
       </div>
      <!-- 当有数据时 -->
       <div class="studentlist" v-if="tableData!='' ||  handadd===false || havelist===true || handData!=''">
         <div class="header">序号</div>
         <div class="header">学号</div>
         <div class="header">姓名</div>
         <div class="header">操作</div>
       </div>

       <!-- 手动添加时 ------------------------------------------------------------------------------------------------------------------------>
       <div class="studentbox" v-if="handData!=''">
        <div class="row" v-for="(item, index) in handData" :key="index">
            <div class="cell"> {{ index+1 }}</div>
            <!-- 学号 -->
              <div class="cell">
                <!-- {{ row['in1'] }} -->
                <input v-if="item.isEditing" v-model="item.stu_no" type="text" />
                <span v-else>{{ item.stu_no }}</span>
              </div>
                <!-- 名字 -->
              <div class="cell">
                 <!-- {{ row['in2'] }} -->
                 <input v-if="item.isEditing" v-model="item.stu_name" type="text" />
                      <span v-else>{{ item.stu_name }}</span>
              </div>
              <!-- 操作 -->
              <div class="cell">
                    <!-- 操作 -->
                  <div class="cell-imgbox">
                    <img src="/public/edit.png" alt="" style="width: 30px; height: 32px;" @click="editsty(item, index)" v-if="!item.isEditing">
                    <img src="/public/saveit.png" alt="" style="width: 30px; height: 30px;" @click="editsty(item, index)" v-else>
                    <a-popconfirm
                      title="真的要删除?"
                ok-text="是的"
    cancel-text="算了"
    @confirm="confirm(item.stu_name,index,item.stu_no)"
    @cancel="cancel"
  >
                    <div>
                    <img src="/public/delete.png" alt="" style="width: 23px; height: 29px;">
                  </div>
                  </a-popconfirm>
                  </div>
              </div>
          </div>
       </div>
       <div v-if="handadd===false || havelist==true" class="draggable" @mousedown="startDrag" :style="{ left: position.x + 'px', top: position.y + 'px' }" @click="addhandtable">点击增加一列</div>
       <view v-if="handadd===false" class="exportxlsx" @click="exportToXLSX">导出为 XLSX</view>
       <view v-if="tableData=='' && handadd!==false && havelist==false" class="downloadxlsx" @click="downloadxlsx">下载模板</view>

<!-- 上传时---------------------------------------------------------------------------------------------------------------------------------->
       <!-- 底部的数据 -->
        <div class="studentbox" v-if="tableData!=''">
          <div class="row" v-for="(row, rowIndex) in tableData" :key="rowIndex">
            <div class="cell"> {{ rowIndex+1 }}</div>
            <!-- 学号 -->
              <div class="cell">
                <!-- {{ row['in1'] }} -->
                <input v-if="row.isEditing" v-model="row['in0']" type="text" />
                <span v-else>{{ row['in0'] }}</span>
              </div>
                <!-- 名字 -->
              <div class="cell">
                 <!-- {{ row['in2'] }} -->
                 <input v-if="row.isEditing" v-model="row['in1']" type="text" />
                      <span v-else>{{ row['in1'] }}</span>
              </div>
              <!-- 操作 -->
              <div class="cell">
                    <!-- 操作 -->
                  <div class="cell-imgbox">
                    <img src="/public/edit.png" alt="" style="width: 30px; height: 32px;" @click="editstyup(row, rowIndex)" v-if="!row.isEditing">
                    <img src="/public/saveit.png" alt="" style="width: 30px; height: 30px;" @click="editstyup(row, rowIndex)" v-else>
                    <a-popconfirm
                      title="真的要删除?"
                ok-text="是的"
    cancel-text="算了"
    @confirm="confirmup(row['in1'],row['in0'],rowIndex)"
    @cancel="cancelup"
  >                   <div>
                    <img src="/public/delete.png" alt="" style="width: 23px; height: 29px;">
                  </div>
                  </a-popconfirm>
                  </div>
              </div>
          </div>
        </div>
  </div>
</div>
</template>

<script  setup>
import TopBar from './components/TopBar'
import { ref,onBeforeUnmount, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useRoute } from 'vue-router';
import * as XLSX from "xlsx";
import axios from 'axios';
const router = useRouter();
const route = useRoute();
const selectedIndex = ref(null);
const selected = ref(0)
const title = ref([]); 
const tableData = ref([]); 
const handData = ref([])
const handadd = ref(true)
const stu_no = ref([])
const stu_name = ref([])
const students = ref([]);
const havelist = ref(false)

// 班级
const class_id = ref(1);
function confirm (value,index,theid){
  console.log("点击了删除",value,"学号",theid)
  apidelete(theid)
  handData.value.splice(index, 1);
  message.success('成功');
};
const cancel = e => {
  console.log(e);
  message.error('已取消');
};

// 本地上传
function confirmup(e,a,index){
  console.log("点击了删除",e,"号码",a)
  tableData.value.splice(index, 1);
  apidelete(a)
  message.success('删除成功');
}

const cancelup = e => {
  console.log(e);
  message.error('已取消');
};

// 移动
const position = ref({ x: 100, y: 100 }); // 初始位置

  const items = [
       { name: '课堂点名', link: '/thestart' },
       { name: '学生名单', link: '/classlist' },
       { name: '首页', link: '/' }
   ];
   const selectedItem = ref(0);
   const selectItem = (index,link) => {
       selectedItem.value = index;
       router.push({ path: link, query: { selectedIndex: index } });
   };
const loading = ref(true)
// const needshow = ref(true)
setTimeout(() => {
  loading.value = false
}, 1000)
onMounted(()=>{
  selectedItem.value = route.query.selectedIndex
  console.log("获得",selectedItem.value)
  selected.value = selectedItem.value
  apigetlist();
})

// 上传
function readFile(file) {
  return new Promise((resolve) => {
    let reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = (ev) => {
      resolve(ev.target.result);
    };
  });
}
const handle = async (ev) => {
  const file = ev.target.files[0]; // 获取上传的文件
  title.value = [];
  tableData.value = [];

  let data = await readFile(file);
  let workbook = XLSX.read(data, { type: "binary" });
  let worksheet = workbook.Sheets[workbook.SheetNames[0]];
  data = XLSX.utils.sheet_to_json(worksheet);

  for (const key in data[0]) {
    title.value.push(key);
  }
  
  data.forEach((item) => {
    let obj = {};
    title.value.forEach((item2, index2) => {
      obj["in" + index2] = item[item2];
    });
    tableData.value.push(obj);
    console.log("得到",tableData.value);
    tableData.value.forEach(item => {
    stu_no.value.push(item.in0);
    stu_name.value.push(item.in1);
    students.value.push({
      stu_no: item.in0,
      stu_name: item.in1
    });
});
console.log("学生编号:", stu_no.value);
console.log("学生姓名:", stu_name.value);
  });
  console.log("完成")
  apiuploadsave();
};


// api文件上传保存
function apiuploadsave(){
  const data = {
    // class_id:class_id.value,
    class_id:2,
    students:students.value
  }
  axios.post('/api/stus/bulk',data).then((res)=>{
      console.log("deddao1",res.data)
      apigetlist()
  })
}

// api获取
function apigetlist(){
  axios.get('/api/stus?class_id=2').then((res)=>{
    console.log(res.data)
    if(res.data.data.length!=0){
      handData.value = res.data.data
      havelist.value = true
      console.log("是不是",havelist.value)
    }else{
      havelist.value = false
      console.log("否则",havelist.value)
    }
  })
}

// 手动添加
function addhandtable() {
      // 添加新行，默认值为空
      handData.value.push({ stu_no: '', stu_name: '' });
}

// 保存
// async function savethisdata(row) {
//   try {
//     const response = await axios.post('/api/stus', {
//       stu_no: row.stu_no,
//       stu_name: row.stu_name,
//       class_id: class_id.value
//     });
//     console.log("得到", response.data);
//   } catch (error) {
//     console.error("保存数据失败:", error);
//   }
// }




// 移动
const startDrag = (event) => {
  const offsetX = event.clientX - position.value.x;
  const offsetY = event.clientY - position.value.y;

  const onMouseMove = (e) => {
    position.value.x = e.clientX - offsetX;
    position.value.y = e.clientY - offsetY;
  };

  const onMouseUp = () => {
    window.removeEventListener('mousemove', onMouseMove);
    window.removeEventListener('mouseup', onMouseUp);
  };

  window.addEventListener('mousemove', onMouseMove);
  window.addEventListener('mouseup', onMouseUp);
};

// 导出
const exportToXLSX = () => {
  const worksheet = XLSX.utils.json_to_sheet(handData.value);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, '学生信息');

  // 生成 XLSX 文件的二进制数据
  const xlsxBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });

  // 创建 Blob 对象
  const blob = new Blob([xlsxBuffer], { type: 'application/octet-stream' });

  // 创建下载链接
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = '学生信息.xlsx'; // 设置下载文件名
  document.body.appendChild(a);
  a.click(); // 模拟点击下载
  document.body.removeChild(a); // 移除链接

  // 释放 Blob URL
  URL.revokeObjectURL(url);
};

// 下载模板
function downloadxlsx() {
    axios({
        url: '/stu-excel-template',
        method: 'GET',
        responseType: 'blob', // 确保响应类型为 blob
    }).then((response) => {
        // 创建一个新的 Blob 对象
        const blob = new Blob([response.data]);
        // 创建一个 URL 对象
        const url = URL.createObjectURL(blob);
        // 创建一个 a 标签
        const a = document.createElement('a');
        a.href = url;
        a.download = 'template.xlsx'; // 设置下载的文件名
        document.body.appendChild(a);
        a.click(); // 触发下载
        document.body.removeChild(a); // 下载后移除 a 标签
        URL.revokeObjectURL(url); // 释放 URL 对象
    }).catch((error) => {
        console.error('下载文件失败', error);
    });
}

// 创建学生信息
// function createstudentinfo(){
//   axios.post('/stus',{
//     stu_no:handData.value.studentId,
//     stu_name:handData.value.studentName,
//     class_id:class_id.value
//   }).then((response)=>{
//       console.log("得到",response.data)
//   })
// }


// api创建或者更新
function apicreateorupdate(item,index){
  axios.post('/api/stus/createOrUpdate',{
    uuid:item.uuid,
    stu_no:item.stu_no,
    stu_name:item.stu_name,
    class_id:class_id.value
  }).then((res)=>{
      console.log(res.data)
  })
}




function tapadd(){
  console.log("点击了添加")
  // needshow.value = !needshow.value
  handadd.value = false
}
function tapinclude(){
  console.log("点击导入")
  // needshow.value = !needshow.value
  const fileInput = document.querySelector('input[type="file"]');
  fileInput.click(); // 触发文件选择
}

// 编辑和删除
function editsty(item, index) {
  // 切换编辑状态
  // row.isEditing = !row.isEditing;
  item.isEditing = !item.isEditing
  if (!item.isEditing) {
    console.log("保存数据", item,"手动",index);
    // savethisdata(row); // 在保存时调用 savethisdata
    apicreateorupdate(item,index)
  }
}

function editstyup(row,index){
  row.isEditing = !row.isEditing;
  if (!row.isEditing) {
    console.log("上传", row,"手动",index);
    // savethisdata(row); // 在保存时调用 savethisdata
    apicreateorupdate(row,index)
  }
}

// function deletesty(e,a){
//   console.log("点击了删除",e,"号码",a)
//   // tableData.value.splice(index, 1);
//   // handData.value.splice(index, 1);
//   apidelete(a)
// }
// api删除
function apidelete(theid){
  // axios.delete(`/api/stus/delete?stu_no=${theid}&class_id=1`)
  //   .then((response) => {
  //     console.log("删除", response.data);
  //   })
  //   .catch((error) => {
  //     console.error("删除失败", error);
  //   });
  axios.post('/api/stus/delete',{
    stu_no:theid,
    class_id:1
  }).then((res)=>{
    console.log("得到",res.data)
  })
}



</script>
<style scoped lang="less">
@import './index.less';
</style>
